package com.spring.boot.controller;

import com.mysql.jdbc.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Enumeration;
import java.util.Map;


public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("login-filter-before");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        System.out.println("TestFilter," + request.getRequestURI());
        String uri = request.getRequestURI();

        HttpSession session = request.getSession(false);
        if ((session == null || session.getAttribute("user") == null) && !uri.contains("/login")) {
            response.sendRedirect("/sso/login.html?preUrl=" +
                    Base64.getEncoder().encodeToString((request.getRequestURL().toString())
                            .getBytes(StandardCharsets.UTF_8)));
            return;
        }

        //执行
        filterChain.doFilter(servletRequest, servletResponse);
        System.out.println("login-filter-after");
    }
}
